
// const mySqlServer = require("../mysql/index.js")
const jwt = require('../models/tokenFn')
// const { getFile } = require('../models/getfile')
const model = require('../models/model')
const { getFile } = require('../models/getfile')
const MyGoodsListRate = model.goodsdetailsRate.MyGoodsListRate
const ShopOrder = model.shopOrder.ShopOrder
const User = model.shopUser.ShopUser

exports.getStatusList = async(ctx) => {
  // const userId = jwt.verify(ctx.header)
  // if (!userId || userId == -1) {
  //   ctx.fail('参数错误', -1)
  //   return
  // }
  const { page, size, status, goodsId } = ctx.request.body
  if (!page || !size) {
    ctx.fail('参数错误', -1)
    return
  }

  // 获取用户信息
  function getUserInfo(userId) {
    return new Promise(async(resolve) => {
      const res = await User.findOne({ where: { userId }})
      const avatar = await getFile(res.avatar)
      resolve({
        userName: res.userName,
        userId: res.userId,
        avatar
      })
    })
  }

  function allFn() {
    return new Promise(async(resolve) => {
      let data = { // 默认参数
        offset: (page-1) * size,
        limit: parseInt(size),
        where: { goodsId }
      }
      switch(status) {
        case 'newest': // 最新时间排序
          data['order'] = [['updateTime', 'DESC']]
          break
        case 'own': // 只看自己的评论
          data['order'] = [['updateTime', 'DESC']]
          data['where']['userId'] = userId
          break
      }
      const res = await MyGoodsListRate.findAndCountAll(data)
      if (res.rows.length > 0) {
        let flag = 0
        for (let i = 0; i < res.rows.length; i++) {
          getUserInfo(res.rows[i].userId).then(userData => {
            res.rows[i].user = userData
            flag++
            if (flag === res.rows.length) {
              resolve(res)
            }
          })
        }
      } else {
        resolve(res)
      }
    })
  }
  const res = await allFn()
  if (res != -1) {
    ctx.success({
      total: res.count, // 总页数
      pageNum: Math.trunc((res.count + (size -1) )/size), // 分页数量
      page: parseInt(page), // 页码
      size: parseInt(size), // 页数
      list: res.rows
    })
  }
}
exports.add = async(ctx) => {
  const userId = jwt.verify(ctx.header)
  if (!userId || userId == -1) {
    ctx.fail('参数错误', -1)
    return
  }
  const { count, description, goodsId, orderId, adminId } = ctx.request.body
  if (!count || !goodsId || !orderId || !adminId) {
    ctx.fail('参数错误', -1)
    return
  }
  function addRate() {
    return new Promise(async(resolve) => {
      // const params = [count, description, goodsId, userId, adminId]
      // const sql = `insert into goodsdetails_rate (count,description,goodsId,userId,orderId,adminId) values (?,?,?,?,?,?)`
      // const res = await mySqlServer.mySql(sql, params)
      const res = await MyGoodsListRate.create(ctx.request.body)
      if (res) {
        resolve(0)
      } else {
        resolve(-1)
      }
    })
  }
  function editOrder() {
    return new Promise(async(resolve) => {
      // const sql = `update shop_order set orderStatus = 'YWC' where id = ${orderId}`
      // const res = await mySqlServer.mySql(sql)
      const res = await ShopOrder.update({ orderStatus: 'YWC' }, {
        where: { orderId: orderId }
      })
      if (res[0] === 1) {
        resolve(0)
      } else {
        resolve(-1)
      }
    })
  }
  const addRate_res = await addRate()
  const editOrder_res = await editOrder()
  if (addRate_res === 0 && editOrder_res === 0) {
    ctx.success('', '评价成功')
  } else {
    ctx.fail('评价失败', -1)
  }
}